package com.jingxian.print.service;

import com.jingxian.print.config.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author xuwei
 * @date 2024年04月17日 18:42
 */
@Slf4j
@Service
public class ImageService {

    @Autowired
    private RedisCache redisCache;

    /**
     * 镜像扩充pdf
     * @param path
     */
    public void doExpandPDF(String path) {
        long time = System.currentTimeMillis();
        try {
            File parent = new File(path);
            File[] files = parent.listFiles();
            for (File file : files) {
                // 加载原始 PDF 文件
                PDDocument document = PDDocument.load(file);
                PDFRenderer pdfRenderer = new PDFRenderer(document);
                int pageCount = document.getNumberOfPages();

                // 创建新的 PDF 文档
                PDDocument newDocument = new PDDocument();

                // 遍历每一页
                for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
                    // 渲染页面为 BufferedImage
                    BufferedImage image = pdfRenderer.renderImageWithDPI(pageIndex, 300, ImageType.RGB);

                    // 扩展边框并镜像内容
                    BufferedImage newImage = this.addBorderAndMirror(image, 100);

                    // 创建新的 PDF 页面
                    PDPage newPage = new PDPage();
                    newDocument.addPage(newPage);

                    // 将 BufferedImage 转换为字节数组
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ImageIO.write(newImage, "png", baos);
                    byte[] imageBytes = baos.toByteArray();

                    // 创建 PDImageXObject
                    PDImageXObject pdImage = PDImageXObject.createFromByteArray(newDocument, imageBytes, "image");

                    // 在新页面上绘制图像
                    try (PDPageContentStream contentStream = new PDPageContentStream(newDocument, newPage)) {
                        contentStream.drawImage(pdImage, 0, 0, newPage.getMediaBox().getWidth(), newPage.getMediaBox().getHeight());
                    }
                }

                // 保存新的 PDF 文件
                newDocument.save(path+"/result/" + file.getName());
                newDocument.close();

                log.info("PDF 转图片并生成新的 PDF 完成。新的 PDF 文件已保存至：{}" ,path+"/result/" + file.getName());
                log.info("处理pdf耗时:{}",(System.currentTimeMillis() - time) / 1000);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 镜像扩充图片
     * @param path
     */
    public void doExpandImageDouble(String path) {
        File parent = new File(path);
        if(!parent.exists()){

        }
        File[] files = parent.listFiles();
        for (File file : files) {
            // 读取原始图像
            BufferedImage originalImage = null;
            try {
                originalImage = ImageIO.read(file);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }

            // 扩展边框并镜像内容
            BufferedImage newImage = this.addBorderAndMirror(originalImage, 100);

            // 将新图像保存到文件
            try {
                File outputImageFile = new File("/Users/chenjingxue/Downloads/image/444444444.png");
                ImageIO.write(newImage, "png", outputImageFile);
                System.out.println("Modified image saved to: " + outputImageFile.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * ps扩充图片
     * @param path
     */
    public void doExpandIamge(String path) {
        String scriptPath = "D:\\ps\\text.jsx";
        String[] command = {"E:\\adobe\\Adobe Photoshop 2021\\Photoshop.exe", scriptPath};
        try {
            // 启动 Photoshop 并执行脚本
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();
            // 等待 Photoshop 执行完成
            int exitCode = process.waitFor();
            System.out.println("Photoshop process exited with code: " + exitCode);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void editjsx(String filePath) {
        Object o = redisCache.getCacheObject("oldFolderPath");
        String oldFolderPath = "";
        if(o != null){
            oldFolderPath = o.toString();
        }

        // 读取文件内容
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(oldFolderPath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 找到包含 folderPath 的行并替换其中的值
                if (line.contains("var folderPath")) {
                    line = "var folderPath = \"" + filePath + "\";";
                }
                contentBuilder.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 将修改后的内容写回文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(oldFolderPath))) {
            writer.write(contentBuilder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public BufferedImage addBorderAndMirror(BufferedImage originalImage, int borderWidth) {
        // 计算新图像尺寸
        int newWidth = originalImage.getWidth() + borderWidth * 2;
        int newHeight = originalImage.getHeight() + borderWidth * 2;

        // 创建新图像
        BufferedImage newImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = newImage.createGraphics();


        // 填充背景色为白色（这里简单地将背景色设置为白色，您可以根据需要调整）
        g2d.setColor(Color.RED);
        g2d.fillRect(0, 0, newWidth, newHeight);

        // 绘制原图像到新图像中间位置
        int xOffset = (newWidth - originalImage.getWidth()) / 2;
        int yOffset = (newHeight - originalImage.getHeight()) / 2;
        g2d.drawImage(originalImage, xOffset, yOffset, null);

        // 镜像边框内容到扩展的边框内
        mirrorBorderContent(originalImage, newImage, borderWidth);

        // 释放资源
        g2d.dispose();

        return newImage;
    }

    private void mirrorBorderContent(BufferedImage originalImage, BufferedImage newImage, int borderWidth) {
        int height = originalImage.getHeight();
        int endX = newImage.getWidth() - borderWidth;
        int endY = newImage.getHeight() - borderWidth;
        // 上边框内容镜像
        for (int x = borderWidth; x < endX; x++) {
            for (int y = 0; y < borderWidth; y++) {
                newImage.setRGB(x, y, originalImage.getRGB(x - borderWidth, borderWidth - y));
            }
        }

        // 下边框内容镜像
        for (int x = borderWidth; x < endX; x++) {
            for (int y = endY; y < newImage.getHeight(); y++) {
                newImage.setRGB(x, y, originalImage.getRGB(x - borderWidth, height - (y - endY) - 1));
            }
        }

        // 左边框内容镜像
        for (int x = 0; x < borderWidth; x++) {
            for (int y = 0; y < newImage.getHeight(); y++) {
                newImage.setRGB(x, y, newImage.getRGB(borderWidth * 2 - x, y));
            }
        }

        // 右边框内容镜像
        for (int x = newImage.getWidth() - 1; x >= endX ; x--) {
            for (int y = 0; y < newImage.getHeight(); y++) {
                newImage.setRGB(x, y, newImage.getRGB(endX - (x - endX) - 1, y));
            }
        }
    }

}
